from django.shortcuts import render, redirect
from django.urls import reverse
from .hive_utils import execute_query, execute_query_schema
table_desc = {
    "piao_fang_top": "票房TOP10电影表",
    "dian_ying_shu_ju": "电影原始数据表",
    "guo_jia_ping_jun_piao_fang": "国家平均票房表",
    "guo_jia_dian_ying_shu": "国家电影数量表",
    "guo_jia_pingfen": "国家电影评分表",
    "yue_fen_dian_ying_shu": "月度电影数量表",
    "dian_ying_leixing_shu": "电影类型数量表",
    "shichang_fen_lei": "电影时长分类表",
    "leixing_pingjun_piaofang": "类型平均票房表",
    "leixing_pingfen": "类型评分占比表",
    "nianfen_pingjun_piaofang": "年度平均票房表",
    "nianfen_dianying_shu": "年度电影数量表",
    "nianfen_pingfen": "年度评分统计表",
    "mei_leixing_piaofang": "各类型票房明细表",
    "mei_leixing_pingfen": "各类型评分明细表",
    "mingxing_dengji": "明星等级分类表",
    "leixing_pingjun_shichang": "类型平均时长表",
    "leixing_zuigao_piaofang": "类型最高票房表"
}
def list_tables(request):
    """列出所有表"""
    query = "SHOW TABLES"

    _, tables = execute_query_schema(query)
    print(tables)
    table_names = [(table[0],table_desc[table[0]]) for table in tables] if tables else []
    return render(request, 'manager/list_tables.html', {'tables': table_names})


def table_detail(request, table_name):
    """显示表数据和结构"""
    # 获取表结构
    desc_query = f"DESCRIBE {table_name}"
    structure = execute_query(desc_query)

    # 获取表数据
    data_query = f"SELECT * FROM {table_name} LIMIT 100"
    data_columns, data = execute_query(data_query)

    context = {
        'table_name': table_name,
        'table_desc': table_desc[table_name],
        'structure': structure,
        'data_columns': data_columns,
        'data': data,
    }
    return render(request, 'manager/table_detail.html', context)


def add_record(request, table_name):
    """添加新记录"""
    if request.method == 'POST':
        # 获取表结构以确定字段
        desc_query = f"DESCRIBE {table_name}"
        structure = execute_query(desc_query)

        # 构建INSERT语句
        fields = [field[0] for field in structure]
        placeholders = ', '.join(['%s'] * len(fields))
        query = f"INSERT INTO {table_name} VALUES ({placeholders})"

        # 从表单获取值
        values = [request.POST.get(field) for field in fields]

        execute_query(query, values)
        return redirect(reverse('table_detail', args=[table_name]))

    # GET请求 - 显示表单
    desc_query = f"DESCRIBE {table_name}"
    structure = execute_query(desc_query)
    print(structure)
    return render(request, 'manager/add_record.html', {
        'table_name': table_name,
        'table_desc': table_desc[table_name],
        'fields': structure
    })


def edit_record(request, table_name, record_id):
    """编辑记录"""
    # 注意: Hive通常不支持直接更新记录，这里假设有一个id字段
    # 实际实现可能需要根据你的Hive表结构调整

    # 获取表结构
    desc_query = f"DESCRIBE {table_name}"
    structure = execute_query(desc_query)
    fields = [field[0] for field in structure]
    id_name = fields[0]
    print("+====",id_name)

    if request.method == 'POST':

        # 构建UPDATE语句 (Hive可能不支持，这里仅为示例)
        # 实际生产环境可能需要使用INSERT OVERWRITE或其他Hive支持的方式
        set_clause = ', '.join([f"{field}=%s" for field in fields if field != id_name])
        query = f"UPDATE {table_name} SET {set_clause} WHERE {id_name}=%s"

        values = [request.POST.get(field) for field in fields if field != id_name]
        values.append(record_id)
        print(record_id)
        print(query)

        execute_query(query, values)

        return redirect(reverse('table_detail', args=[table_name]))

    # GET请求 - 显示编辑表单
    query = f"SELECT * FROM {table_name} WHERE {id_name}=%s"
    _, result = execute_query(query, [record_id])
    print(result)
    record = result[0] if result else None

    desc_query = f"DESCRIBE {table_name}"
    structure = execute_query(desc_query)
    structure = [col[0] for col in structure]
    data = list(zip(structure, list(record)))
    print(data)

    return render(request, 'manager/edit_record.html', {
        'table_name': table_name,
        'table_desc': table_desc[table_name],
        'record_id': record_id,
        'data': data
    })


def delete_record(request, table_name, record_id):

    # 获取表结构
    desc_query = f"DESCRIBE {table_name}"
    structure = execute_query(desc_query)
    fields = [field[0] for field in structure]
    id_name = fields[0]

    """删除记录"""
    # 注意: Hive通常不支持直接删除记录，这里仅为示例
    # 实际实现可能需要使用INSERT OVERWRITE或其他方式
    query = f"DELETE FROM {table_name} WHERE {id_name}=%s"
    execute_query(query, [record_id])
    return redirect(reverse('table_detail', args=[table_name]))
